package com.cskaoyan.demo.filter;

import com.cskaoyan.demo.bean.common.BaseRespVo;
import com.cskaoyan.demo.exception.InfoExpiredException;
import com.cskaoyan.demo.exception.NoInfoException;
import com.cskaoyan.demo.util.AuthenticationUtil;
import com.cskaoyan.demo.util.ResponseUtil;
import com.cskaoyan.demo.util.WdConstant;
import com.cskaoyan.demo.util.WdTokenHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationInfoFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 过滤逻辑
        // 1. 解决跨域问题
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "*");
        response.addHeader("Access-Control-Allow-Headers", "*");

        if (request.getMethod().equals("OPTIONS") || request.getRequestURI().endsWith("/login")) {
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getRequestURI().startsWith("/wx/good")) {
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getRequestURI().startsWith("/wx/catalog")) {
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getRequestURI().startsWith("/wx/home/index")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 2. 放行静态资源访问
        if (request.getRequestURI().startsWith("/wx/storage/fetch")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 3. 根据钥匙获取登录信息
        String token = request.getHeader(WdConstant.MARKET_TOKEN);
        AuthenticationUtil.setToken(token);

        try {
            Object info = WdTokenHolder.getInfo(token);
            filterChain.doFilter(request, response);
        } catch (NoInfoException e) {
            e.printStackTrace();
            ResponseUtil.responseJson(response, BaseRespVo.unAuthc());
        } catch (InfoExpiredException e) {
            e.printStackTrace();
            ResponseUtil.responseJson(response, BaseRespVo.expired());
        }
    }
}
